package org.whuims.pois.action;

import org.apache.logging.log4j.core.helpers.Strings;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import org.whuims.pois.action.result.SearchBean;
import org.whuims.pois.action.result.SearchResult;
import org.whuims.pois.common.Chinese;
import org.whuims.pois.dao.SearchDao;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Created by zhongwei on 2014/5/21.
 */
public class SearchAction extends DispatchAction {
    SearchDao searchDao = new SearchDao();

    public ActionForward search(ActionMapping mapping, ActionForm form,
                                HttpServletRequest request, HttpServletResponse response) {
        SearchBean bean = (SearchBean) form;
        String pageStr = request.getParameter("page");
        String sizeStr = request.getParameter("size");
        String from = request.getParameter("from");
        if (from != null && from.equalsIgnoreCase("top")) {
            pageStr = "0";
        }
        int page = 0;
        if (Strings.isNotEmpty(pageStr)) {
            try {
                page = Integer.parseInt(pageStr);
            } catch (NumberFormatException e) {
                page = 0;
            }
        }
        if (page >= 750) {
            page = 750;
        }
        int size = 10;
        if (Strings.isNotEmpty(sizeStr)) {
            try {
                size = Integer.parseInt(sizeStr);
            } catch (NumberFormatException e) {
                size = 10;
            }
        }
        bean.setPage(page);
        bean.setSize(size);

        if ((from == null || !from.equalsIgnoreCase("top"))) {

            if (Strings.isNotEmpty(bean.getKeyword())) {
                bean.setKeyword(Chinese.toChinese(bean.getKeyword()));
            }
            if (Strings.isNotEmpty(bean.getTitle())) {
                bean.setTitle(Chinese.toChinese(bean.getTitle()));
            }
            if (Strings.isNotEmpty(bean.getSite())) {
                bean.setSite(Chinese.toChinese(bean.getSite()));
            }
        }


        SearchResult dataVos = searchDao.search(bean, request, page, size);
        request.setAttribute("result", dataVos);
        request.setAttribute("search", bean);
        return mapping.findForward("success");
    }
}
